package com.glsc.ngateway.opmanage.controller.outsys;

import com.glsc.ngateway.common.api.common.utils.PageUtil;
import com.glsc.ngateway.common.api.platform.resp.PlatformResponse;
import com.glsc.ngateway.common.base.domain.mysql.opmanagemain.outsys.OutSystemAuthInfo;
import com.glsc.ngateway.common.base.domain.mysql.opmanagemain.outsys.OutSystemInfo;
import com.glsc.ngateway.opmanage.dto.OutSystemAuthIdsDto;
import com.glsc.ngateway.opmanage.dto.OutSystemExcelDto;
import com.glsc.ngateway.opmanage.dto.OutSystemQueryDto;
import com.glsc.ngateway.opmanage.dto.OutSystemUserDto;
import com.glsc.ngateway.opmanage.service.outsys.OutSystemService;
import com.glsc.ngateway.opmanage.utils.report.ReportFileConfigEnum;
import com.glsc.ngateway.opmanage.utils.report.ReportFileUtil;
import com.glsc.ngateway.opmanage.utils.report.ReportUploadContext;
import com.google.common.collect.Lists;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

/**
 * 外部系统权限管理
 */
@RestController
@RequestMapping("/api/outSystem")
@Slf4j
public class OutSystemController {

    @Resource
    private OutSystemService outSystemService;


    /**
     * 分页查询
     *
     * @param outSystemQueryDto
     * @return
     */
    @PostMapping("/page")
    public PlatformResponse<Page<OutSystemAuthInfo>> findClientPage(@RequestBody OutSystemQueryDto outSystemQueryDto) {

        Map<String, Object> param = new HashMap<>();
        if (StringUtils.isNotBlank(outSystemQueryDto.getSystemName())) {
            param.put("LIKE_systemName", outSystemQueryDto.getSystemName());
        }
        if (StringUtils.isNotBlank(outSystemQueryDto.getAuthName1())) {
            param.put("LIKE_authName1", outSystemQueryDto.getAuthName1());
        }
        if (StringUtils.isNotBlank(outSystemQueryDto.getAuthName2())) {
            param.put("LIKE_authName2", outSystemQueryDto.getAuthName2());
        }
        if (StringUtils.isNotBlank(outSystemQueryDto.getAuthName3())) {
            param.put("LIKE_authName3", outSystemQueryDto.getAuthName3());
        }
        if (StringUtils.isNotBlank(outSystemQueryDto.getAuthName4())) {
            param.put("LIKE_authName4", outSystemQueryDto.getAuthName4());
        }
        if (StringUtils.isNotBlank(outSystemQueryDto.getAuthName5())) {
            param.put("LIKE_authName5", outSystemQueryDto.getAuthName5());
        }
        if (StringUtils.isNotBlank(outSystemQueryDto.getDeptName())) {
            param.put("LIKE_deptName", outSystemQueryDto.getDeptName());
        }
        if (StringUtils.isNotBlank(outSystemQueryDto.getPostName())) {
            param.put("LIKE_postName", outSystemQueryDto.getPostName());
        }
        if (StringUtils.isNotBlank(outSystemQueryDto.getOperatorName())) {
            param.put("LIKE_operatorName", outSystemQueryDto.getOperatorName());
        }
        Page<OutSystemAuthInfo> page = outSystemService.page(PageUtil.initPageNo(outSystemQueryDto.getPageNo()), PageUtil.initPageSize(outSystemQueryDto.getPageSize()), param);
        return PlatformResponse.successData(page);
    }

    /**
     * 根据客户id查询客户信息
     *
     * @param
     * @return
     */
    @GetMapping("/findById")
    public PlatformResponse<OutSystemAuthInfo> findById(@ApiParam(value = "id") @RequestParam(required = true) Integer id) {
        return PlatformResponse.successData(outSystemService.findById(id));
    }

    /**
     * 保存
     *
     * @param outSystemAuthInfo
     * @return
     */
    @PostMapping("/save")
    public PlatformResponse<OutSystemAuthInfo> save(@RequestBody OutSystemAuthInfo outSystemAuthInfo) {
        return PlatformResponse.successData(outSystemService.save(outSystemAuthInfo));
    }

    /**
     * 从模板创建用户
     *
     * @param dto
     * @return
     */
    @PostMapping("/saveFromTemplate")
    public PlatformResponse<?> saveFromTemplate(@RequestBody OutSystemUserDto dto) {

        outSystemService.saveFromTemplate(dto);

        return PlatformResponse.success();
    }

    /**
     * 删除接口
     *
     * @return
     */
    @PostMapping("/delete")
    public PlatformResponse<?> delete(@RequestBody OutSystemAuthInfo outSystemAuthInfo) {
        outSystemService.deleteById(outSystemAuthInfo.getId());
        return PlatformResponse.success();
    }

    /**
     * 启用禁用
     *
     * @param id
     * @param enable
     * @return
     */
    @GetMapping("/enable")
    public PlatformResponse<OutSystemAuthInfo> enable(@ApiParam(value = "id") @RequestParam(required = true) Integer id, @ApiParam(value = "启用禁用标识") @RequestParam(required = true) String enable) {
        return PlatformResponse.successData(outSystemService.enable(id, enable));
    }


    /**
     * 导入
     *
     * @param file
     * @param opSystemName
     * @return
     * @throws IOException
     */
    @PostMapping("/import")
    @ApiOperation(value = "外部系统权限管理导入", notes = "外部系统权限管理导入")
    public PlatformResponse<?> outSystemImport(@RequestPart("file") MultipartFile file, @ApiParam(value = "系统名称") @RequestParam(required = true) String opSystemName) throws IOException {
        log.info("外部系统权限管理导入,【{}】的数据发生导入", opSystemName);
        ReportUploadContext<OutSystemExcelDto, String> context = outSystemService.ousSystemImport(file, opSystemName);
        return context.isCheckPass() ? PlatformResponse.successData(context.getReadRes()) : PlatformResponse.failedMsg(String.join(",", context.getCheckRes()));
    }

    /**
     * 导出接口不分页
     *
     * @param outSystemQueryDto
     * @param response
     * @return
     * @throws IOException
     */
    @PostMapping("/export")
    public byte[] export(@RequestBody OutSystemQueryDto outSystemQueryDto, HttpServletResponse response) throws IOException {

        response.setHeader("Content-Disposition", "attachment;" + "filename=" + URLEncoder.encode(ReportFileConfigEnum.OUT_SYSTEM_EXPORT.getFileName(), "UTF-8"));

        Map<String, Object> param = new HashMap<>();
        if (StringUtils.isNotBlank(outSystemQueryDto.getSystemName())) {
            param.put("LIKE_systemName", outSystemQueryDto.getSystemName());
        }
        if (StringUtils.isNotBlank(outSystemQueryDto.getAuthName1())) {
            param.put("LIKE_authName1", outSystemQueryDto.getAuthName1());
        }
        if (StringUtils.isNotBlank(outSystemQueryDto.getAuthName2())) {
            param.put("LIKE_authName2", outSystemQueryDto.getAuthName2());
        }
        if (StringUtils.isNotBlank(outSystemQueryDto.getAuthName3())) {
            param.put("LIKE_authName3", outSystemQueryDto.getAuthName3());
        }
        if (StringUtils.isNotBlank(outSystemQueryDto.getAuthName4())) {
            param.put("LIKE_authName4", outSystemQueryDto.getAuthName4());
        }
        if (StringUtils.isNotBlank(outSystemQueryDto.getAuthName5())) {
            param.put("LIKE_authName5", outSystemQueryDto.getAuthName5());
        }
        if (StringUtils.isNotBlank(outSystemQueryDto.getDeptName())) {
            param.put("LIKE_deptName", outSystemQueryDto.getDeptName());
        }
        if (StringUtils.isNotBlank(outSystemQueryDto.getPostName())) {
            param.put("LIKE_postName", outSystemQueryDto.getPostName());
        }
        if (StringUtils.isNotBlank(outSystemQueryDto.getOperatorName())) {
            param.put("LIKE_operatorName", outSystemQueryDto.getOperatorName());
        }
        Page<OutSystemAuthInfo> page = outSystemService.page(1, 9999, param);

        if (Objects.isNull(page) || CollectionUtils.isEmpty(page.getContent())) {
            return null;
        }
        Map<Integer, OutSystemInfo> map = new HashMap<>();
        List<OutSystemExcelDto> resList = Lists.newArrayList();
        for (OutSystemAuthInfo info : page.getContent()) {
            OutSystemInfo outSystemInfo = map.get(info.getSysId());
            if (Objects.isNull(outSystemInfo)) {
                outSystemInfo = outSystemService.findSystemById(info.getSysId());
                if (Objects.nonNull(outSystemInfo)) {
                    map.put(outSystemInfo.getId(), outSystemInfo);
                }
            }
            resList.add(OutSystemExcelDto.builder().systemName(outSystemInfo.getSysName()).authName1(info.getAuthName1()).authName2(info.getAuthName2()).authName3(info.getAuthName3()).authName4(info.getAuthName4())
                    .authName5(info.getAuthName5()).deptName(info.getDeptName()).postName(info.getPostName()).operatorName(info.getOperatorName()).userName(info.getUserName()).userAccount(info.getUserAccount()).build());
        }

        return ReportFileUtil.export(resList, ReportFileConfigEnum.OUT_SYSTEM_EXPORT);
    }

    @PostMapping("/deleteByIds")
    public PlatformResponse<?> deleteByIds(@RequestBody OutSystemAuthIdsDto outSystemAuthInfo) {
        if (CollectionUtils.isNotEmpty(outSystemAuthInfo.getIds())) {
            outSystemService.deleteByIds(outSystemAuthInfo.getIds());
        }
        return PlatformResponse.success();
    }


    /**
     * 查询所有系统信息，下拉列表使用
     *
     * @return
     */
    @GetMapping("/listAllUseFullSystem")
    public PlatformResponse<?> listAllUseFullSystem() {
        return PlatformResponse.successData(outSystemService.listAllUseFullSystem());
    }

    @GetMapping("/sendOafLow")
    public PlatformResponse<?> sendOafLow() {
        outSystemService.createOaFlow();
        return PlatformResponse.success();
    }

}
